package com.study.aspect;

import com.google.common.util.concurrent.RateLimiter;
import com.study.anno.ApiRateLimit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzi
 * 2024/9/26 10:44
 * 原文链接：https://blog.csdn.net/mbh12333/article/details/137879894
 * https://www.cnblogs.com/ooo0/p/15013894.html#
 */
@Aspect
@Component
public class ApiRateLimitAspect {
    private final static Map<String, RateLimiter> rateLimiters = new ConcurrentHashMap<>();


    @Around("@annotation(apiRateLimit)")
    public Object pointcut(ProceedingJoinPoint point, ApiRateLimit apiRateLimit) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        // rate limiter cache key -> package name + method name (eg:"com.alibaba.comtroller.getUser")
        String key = methodSignature.getDeclaringTypeName() + "." + method.getName();
        ApiRateLimit rateLimit = AnnotationUtils.findAnnotation(method, ApiRateLimit.class);
        if (apiRateLimit != null) {
            double value = rateLimit.qps();
            long timeout = rateLimit.timeout();
            TimeUnit timeUnit = rateLimit.timeUnit();
            RateLimiter rateLimiter = rateLimiters.computeIfAbsent(key, k -> RateLimiter.create(value));
            if (rateLimiter == null || !rateLimiter.tryAcquire(timeout, timeUnit)) {

                System.out.println(method.getName() + "interface rate limit");
                return "同时调用次数过多，请稍后再试!";
            }
        }
        return point.proceed();
    }

    //@Before("@annotation(apiRateLimit)")
    public void limit(JoinPoint joinPoint, ApiRateLimit apiRateLimit) {
        String typeName = joinPoint.getSignature().getDeclaringTypeName();
        String name = joinPoint.getSignature().getName();
        double qps = apiRateLimit.qps();
        RateLimiter limiter = rateLimiters.computeIfAbsent(typeName + name, k -> RateLimiter.create(qps));
        long timeout = apiRateLimit.timeout();
        TimeUnit timeUnit = apiRateLimit.timeUnit();
        if (timeout > 0) {
            if (!limiter.tryAcquire(timeout, timeUnit)) {
                throw new RuntimeException("API rate limit exceeded");
            }
        } else {
            if (!limiter.tryAcquire()) {
                throw new RuntimeException("API rate limit exceeded");
            }
        }
    }
}
